import { useState, useEffect } from 'react'
import { GetListFnc, GetAttrFnc } from '@/api/params'
import style from './index.module.scss'
import { Breadcrumb, Alert, Cascader, Tabs } from 'antd'
import Tables from './components/Tables'


const Params = () => {
  const [options, setOptions] = useState([]) // 级联选择器  
  const [btnDisabled, setBtnDisabled] = useState(true) // 添加参数 或者 属性 按钮
  const [dataSource, setDataSource] = useState([]) // 表格数据
  const [cascaderValue, setCascaderValue] = useState('') // 级联选择器的值
  const [activeName, setActiveName] = useState('many') // many=参数  only=属性
  const [catID, setCatID] = useState(0) // catID的值
  

  // 获取table数据  
  const getTable = async (cascaderVal: string, activeNameVal: string) => {
    const res = await GetAttrFnc(parseInt(cascaderVal), {sel: activeNameVal})
    if(res.data.meta.status === 200 && res.data.data.length !== 0) {
      setDataSource(res.data.data)
      setBtnDisabled(false)
    }
  }

  const tabItems = [
    { key: 'many', label: '动态参数', children: <Tables dataSource={dataSource} cascaderValue={cascaderValue} getTable={getTable} catID={catID} btnDisabled={btnDisabled} activeName={activeName}/>},
    { key: 'only', label: '静态属性', children: <Tables dataSource={dataSource} cascaderValue={cascaderValue} getTable={getTable} catID={catID} btnDisabled={btnDisabled} activeName={activeName}/>}
  ]

  // 级联数据初始化
  const init = async () => {
    const res = await GetListFnc()
    if(res.data.meta.status === 200) setOptions(res.data.data)
  }
  useEffect(() => { init() }, [])

  // 级联选择器 获取table数据  
  const getTableData = async (value: any[]) => {
    if(value !== undefined) {
      setCascaderValue(value[value.length - 1])
      getTable(value[value.length - 1], activeName)
      setCatID(value[value.length - 1])
    }
  }
  
  // tab切换 获取table数据  
  const tabChange = async(value: string) => {
    setActiveName(value)
    if(cascaderValue !== '') {
      getTable(cascaderValue, value)
    }
  }

  // 清除级联选择器
  const clearSelect = () => {
    setBtnDisabled(true)
    setDataSource([])
  }

  return (
    <>
      <Breadcrumb items={[{ title: '商品管理' }, { title: '参数列表' }]} />

      <div className={style.paramsContent}>
        <Alert message="注意:只允许为第三级分类设置相关参数!" type="warning" showIcon />

        {/* 商品级联选择器 */}
        <div className={style.select}>
          <span>选择商品分类: </span>
          <Cascader style={{width: 200}} options={options} onChange={getTableData} onClear={clearSelect} fieldNames={{label: 'cat_name', value: 'cat_id', children: 'children'}}  placeholder="--请选择--" />
        </div>

        {/* 选项卡 */}
        <Tabs items={tabItems} onChange={tabChange}/>
      </div>
    </>
  )
}

export default Params